chance = new require('chance')()
Promise = require 'bluebird'
request = require 'request'
requestPost = Promise.promisify request.post.bind(request)

error = require '../error'
config = require '../config'
log = require '../log'

nodemailer = require 'nodemailer'
transporter = nodemailer.createTransport
    service: 'QQex',
    auth:
        user: config.serviceMail,
        pass: config.serviceMailPass

pTransporterSendMail = Promise.promisify transporter.sendMail.bind(transporter)

securityCodes = {}

generateSecurityCode = (address) ->
    code = chance.string length: 6, pool: '0123456789'
    securityCodes[address] = {code: code, sendTime: new Date().getTime()}
    code

# 发送验证码到手机
exports.gSendSecurityCodeToPhone = (phone, purpose)->
    code = generateSecurityCode(phone)

    message = new Buffer("@1@=#{purpose},@2@=#{code}", 'utf8').toString('utf8')

    postData =
        method: "sendUtf8Msg"
        username: config.sms.username
        password: config.sms.password
        veryCode: config.sms.veryCode
        mobile: phone
        content: message,
        msgtype: 2
        tempid: config.sms.template,
        code: "utf-8"

    r = yield requestPost config.sms.url, {
        form: postData,
        headers: {'Content-Type': 'application/x-www-form-urlencoded; charset=utf-8'}
    }
    return r.body?.match('<status>0</status>')?.length > 0

# 发邮件消息
pSendEmail = (address, subject, content)->
    mailOptions =
        from: config.serviceMail
        to: address
        subject: subject
        text: content

    pTransporterSendMail mailOptions

# 发送验证码到邮箱
exports.gSendSecurityCodeToEmail = (email, subject, purpose)->
    code = generateSecurityCode(email)
    yield pSendEmail(email, subject, "#{purpose}。您本次操作的验证码是#{code}")

# 验证验证码
exports.check = (target, code)->
    unless securityCodes[target]? && securityCodes[target].code == code
        throw new error.UserError("SecurityCodeNotMatch")
    if new Date().getTime() - securityCodes[target].sendTime > 15 * 60 * 1000
        throw new error.UserError("SecurityCodeExpired") # 过期

    securityCodes[target].used = true